package com.lagou.demo4;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //由于在后面实现了OperaterStateDemo，所以在这里要设置checkpoint的时间间隔,并将数据该从socket读取
        env.enableCheckpointing(2000);
        //
        DataStreamSource<String> data = env.socketTextStream("zb26105", 7777);
        //转换
        SingleOutputStreamOperator<Tuple2<Long, Long>> maped = data.map(new MapFunction<String, Tuple2<Long, Long>>() {
            @Override
            public Tuple2<Long, Long> map(String s) throws Exception {
                String[] split = s.split(",");
                return new Tuple2<Long, Long>(Long.valueOf(split[0]), Long.valueOf(split[1]));
            }
        });



        //1、获取数据源（测试用）
       // DataStreamSource<Tuple2<Long, Long>> data = env.fromElements(new Tuple2(1l, 3l), new Tuple2(1l, 5l), new Tuple2(1l, 7l), new Tuple2(1l, 4l), new Tuple2(1l, 2l));

        //2、分组
        KeyedStream<Tuple2<Long, Long>, Long> keyed = maped.keyBy(value -> value.f0);

        //3、按照key分组策略，对流式数据调用状态化处理
        SingleOutputStreamOperator<Tuple2<Long, Long>> flatMaped = keyed.flatMap(new RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>>() {
            ValueState<Tuple2<Long, Long>> sumState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //在open方法中做出stat,先要有一个descriptor，再调用getStat
                //ValueStateDescriptor中三个参数分别是 state的名称、state的类型，state的初始值
                ValueStateDescriptor<Tuple2<Long, Long>> descriptor = new ValueStateDescriptor<>("average"  //
                        , TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {
                })
                        , Tuple2.of(0L, 0L)

                );
                sumState = getRuntimeContext().getState(descriptor);

                super.open(parameters);
            }

            @Override
            public void flatMap(Tuple2<Long, Long> value, Collector<Tuple2<Long, Long>> out) throws Exception {
                //在flatMap方法中，更新State
                //通过value获取state的值
                Tuple2<Long, Long> currentSum = sumState.value();
                currentSum.f0 += 1;
                currentSum.f1 += value.f1;

                sumState.update(currentSum);

                //以怎样的频率计算平均值，如下面，来2个数据会计算一次平均值，并将平均值输出到sink
                if (currentSum.f0 == 2){
                    long avarage =  currentSum.f1/currentSum.f0;
                    out.collect(new Tuple2(value.f0, avarage));
                    sumState.clear();
                }

            }
        });

//        flatMaped.print();
        //阈值为5，也就是需要接受5个平均值，才能触发后面的输出，所以说此时需要输入10个原始数据，才能触发
        flatMaped.addSink(new OperaterStateDemo(5));

        env.execute();

    }
}
